import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import viteCompression from 'vite-plugin-compression';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import vitePluginExternal from 'vite-plugin-external';

// 全局对象
const externalGlobalsObj = {
  vue: 'Vue3',
  'element-plus': 'ElementPlus',
  // vuex: "Vuex",
};

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const isDEV = mode === 'development' || env.VITE_APP_ONLINE_DEVELOPMENT_MODE === 'true';
  return {
    base: './',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
      extensions: ['.js', '.json', '.ts', '.vue'],
    },
    plugins: [
      vue(),
      cssInjectedByJsPlugin(), // 将css打进js
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz',
      }),
      vitePluginExternal({
        externals: externalGlobalsObj,
        mode: false,
      }),
    ],
    server: {
      host: '0.0.0.0',
      open: true,
      hmr: true,
      proxy: {
        '/api': {
          target: 'http://10.15.111.15:8088/',
          changeOrigin: true,
          rewrite: path => path.replace('/api', ''),
        },
      },
    },
    esbuild: {
      pure: isDEV ? [] : ['console.log', 'debugger'],
    },
    build: {
      target: 'es2015',
      sourcemap: env.VITE_APP_BUILD_SOURCE_MAP === 'true' ? 'inline' : false,
      rollupOptions: {
        output: {
          entryFileNames: 'assets/app.[hash].js',
          assetFileNames: 'media/[name]-[hash].[ext]',
        },
      },
    },
  };
});
